//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//

package com.ty.pdm.system.workFlow.listener.common;

import cn.hutool.extra.spring.SpringUtil;
import com.alibaba.fastjson.JSONObject;
import com.hustcad.plm.pdm.baseline.service.TyplmBaseLineMemberService;
import com.hustcad.plm.pdm.baseline.service.TyplmBaseLineService;
import com.hustcad.plm.pdm.ec.module.dto.ECObjDTO;
import com.hustcad.plm.pdm.ec.module.dto.ECObjData;
import com.hustcad.plm.pdm.flowbusiness.model.entity.FlowChgFormView;
import com.hustcad.plm.pdm.flowbusiness.model.entity.FlowObject;
import com.hustcad.plm.pdm.flowbusiness.model.entity.WorkFlowObjectPackage;
import com.hustcad.plm.pdm.partbom.dto.ChildPartsFiltersDTO;
import com.hustcad.plm.pdm.partbom.dto.PartBomTree;
import com.hustcad.plm.pdm.partbom.service.TyplmPartBomService;
import com.hustcad.plm.pdm.partbom.service.TyplmPartService;
import com.hustcad.plm.pdm.partbom.vo.PartBomTreeByFilterVO;
import com.hustcad.plm.pdm.partbom.vo.PartDetailsVO;
import com.hustcad.plm.pdm.workflow.annotion.CustomListener;
import com.hustcad.plm.pdm.workflow.annotion.CustomListenerField;
import com.hustcad.plm.pdm.workflow.model.entity.WorkFlowContainerView;
import com.hustcad.plm.pdm.workflow.service.TyplmWorkFlowContainerService;
import com.jsyxdl.k3cloud.listener.K3CloudHttpService;
import com.jsyxdl.k3cloud.utils.HttpMethodEnum;
import com.jsyxdl.k3cloud.utils.PlmPartOptionUtils;
import com.jsyxdl.k3cloud.utils.SendErpDataUtils;
import com.ty.basic.exception.message.SystemErrorCodeEnum;
import org.flowable.engine.delegate.DelegateExecution;
import org.flowable.engine.delegate.ExecutionListener;
import org.flowable.engine.impl.el.FixedValue;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@CustomListener(
        category = "BOM数据校验",
        description = "BOM数据校验"
)
public class BOMVerificationLineListener implements ExecutionListener {
    private static final Logger log = LoggerFactory.getLogger(BOMVerificationLineListener.class);
    private static final long serialVersionUID = -9059663559349037414L;

    @CustomListenerField(
            description = "是否处理Desing视图",
            defaultValue = "",
            required = true
    )
    private FixedValue desing;
    @CustomListenerField(
            description = "是否成品校验",
            defaultValue = "",
            required = true
    )
    private FixedValue cpCheck;

    public void notify(DelegateExecution execution) {
        try {
            log.info("开始执行监听 ==> 物料申请 BaseLineListener");
            String workFlowContainerIdStr = execution.getProcessInstanceBusinessKey();
            BigInteger workFlowContainerId = new BigInteger(workFlowContainerIdStr);
            TyplmWorkFlowContainerService typlmWorkFlowContainerService = SpringUtil.getBean(
                    TyplmWorkFlowContainerService.class);
            PlmPartOptionUtils plmPartOptionUtils = SpringUtil.getBean(PlmPartOptionUtils.class);



            if (typlmWorkFlowContainerService != null) {
                WorkFlowContainerView workFlowContainerView = typlmWorkFlowContainerService.getWorkFlowContainerDetailByPrimaryKey(
                        workFlowContainerId);
                if (workFlowContainerView instanceof WorkFlowObjectPackage) {
                    WorkFlowObjectPackage workFlowObjectPackage = (WorkFlowObjectPackage) workFlowContainerView;
                    if (workFlowObjectPackage.getFlowObjectList() != null && workFlowObjectPackage.getFlowObjectList()
                            .size() != 0) {

                        if(this.cpCheck!=null && "是".equals(this.cpCheck.getExpressionText())){
                            boolean cp=false;
                            for (int i = 0; i < workFlowObjectPackage.getFlowObjectList().size(); i++){
                                FlowObject flowObject = workFlowObjectPackage.getFlowObjectList().get(i);
                                BigInteger coid = flowObject.getRefObjectOid();
                                String coType = flowObject.getRefObjectOtype();
                                PartDetailsVO partDetails = plmPartOptionUtils.getPartDetailsVO(coid, coType);
                                if("成品".equals(partDetails.getTypeName())){
                                    cp=true;
                                    break;
                                }

                                String classDisplayName=partDetails.getClassDisplayName();
                                if(classDisplayName.indexOf("总成")!= -1){
                                    cp=true;
                                    break;
                                }
                            }
                            if(cp==false){
                                throw SystemErrorCodeEnum.WORK_FLOW_CONTENT_ERROR.getException("没有有效成品产品，请检查类型或分类");
                            }
                        }

                        for (int i = 0; i < workFlowObjectPackage.getFlowObjectList().size(); i++) {
                            FlowObject flowObject = workFlowObjectPackage.getFlowObjectList().get(i);

                            String oType = flowObject.getRefObjectOtype();
                            if ("ty.inteplm.part.CTyPart".equals(oType)) {

                                if (this.desing != null && "是".equals(this.desing.getExpressionText())) {

                                } else {
                                    BigInteger coid = flowObject.getRefObjectOid();
                                    String coType = flowObject.getRefObjectOtype();
                                    PartDetailsVO partDetails = plmPartOptionUtils.getPartDetailsVO(coid, coType);
                                    if ("Design".equals(partDetails.getPartView())) {
                                        continue;
                                    }
                                }
                            }

                            extendedTask(flowObject);
                        }
                    } else {
                        throw SystemErrorCodeEnum.WORK_FLOW_CONTENT_ERROR.getException("getFlowObjectList为空");
                    }
                }
                else if (workFlowContainerView instanceof FlowChgFormView) {
                    FlowChgFormView flowChgFormView = (FlowChgFormView) workFlowContainerView;
                    if (flowChgFormView.getChgFormVO() != null && flowChgFormView.getChgFormVO()
                            .getEcObjDataVOS() != null) {



                        List<FlowObject> flowObjectList=new ArrayList<>();
                        for (int i = 0; i < flowChgFormView.getChgFormVO().getEcObjDataVOS().size(); i++) {
                            ECObjData ecObjData = flowChgFormView.getChgFormVO().getEcObjDataVOS().get(i);
                            BigInteger partOid = ecObjData.getRefObjectOid();
                            String oType = ecObjData.getRefObjectOtype();
                            FlowObject flowObject=new FlowObject();
                            flowObject.setRefObjectOid(partOid);
                            flowObject.setRefObjectOtype(oType);
                            flowObjectList.add(flowObject);
                        }

                        if(this.cpCheck!=null && "是".equals(this.cpCheck.getExpressionText())){
                            boolean cp=false;
                            for (int i = 0; i < flowObjectList.size(); i++){
                                FlowObject flowObject = flowObjectList.get(i);
                                BigInteger coid = flowObject.getRefObjectOid();
                                String coType = flowObject.getRefObjectOtype();
                                PartDetailsVO partDetails = plmPartOptionUtils.getPartDetailsVO(coid, coType);

                                if(this.desing!=null && "是".equals(this.desing.getExpressionText())){

                                }
                                else{
                                    if("Design".equals(partDetails.getPartView())){
                                        continue;
                                    }
                                }

                                if("成品".equals(partDetails.getTypeName())){
                                    cp=true;
                                    break;
                                }

                                String classDisplayName=partDetails.getClassDisplayName();
                                if(classDisplayName.indexOf("总成")!= -1){
                                    cp=true;
                                    break;
                                }
                            }
                            if(cp==false){
                                throw SystemErrorCodeEnum.WORK_FLOW_CONTENT_ERROR.getException("没有有效成品产品，请检查类型或分类");
                            }
                        }

                        //排除重复的编码
                        Map<String, Object> cmd = new HashMap<>();
                        if(flowChgFormView.getChgFormVO().getEcObjDataVOS()!=null){
                            for (int i = 0; i < flowChgFormView.getChgFormVO().getEcObjDataVOS().size(); i++) {
                                ECObjData ecObjData = flowChgFormView.getChgFormVO().getEcObjDataVOS().get(i);
                                if (cmd.containsKey(ecObjData.getNumber())) {
                                    continue;
                                } else {
                                    cmd.put(ecObjData.getNumber(), "1");
                                }

                                String oType = ecObjData.getRefObjectOtype();
                                if ("ty.inteplm.part.CTyPart".equals(oType)) {

                                    if(this.desing!=null && "是".equals(this.desing.getExpressionText())){

                                    }
                                    else{

                                        BigInteger coid = ecObjData.getRefObjectOid();
                                        PartDetailsVO partDetails = plmPartOptionUtils.getPartDetailsVO(coid, oType);
                                        if("Design".equals(partDetails.getPartView())){
                                            continue;
                                        }
                                    }

                                }

                                extendedTaskEco(ecObjData);
                            }
                        }
                    }
                }
                else {
                    throw SystemErrorCodeEnum.WORK_FLOW_CONTENT_ERROR.getException("WorkFlowObjectPackage错误");
                }
            } else {
                throw SystemErrorCodeEnum.WORK_FLOW_CONTENT_ERROR.getException("TyplmWorkFlowContainerService无法加载");
            }

            log.info("正常执行监听结束 <== 物料申请 BaseLineListener");
        } catch (Exception var5) {
            var5.printStackTrace();
            log.error("监听BaseLineListener异常：" + var5);
            throw SystemErrorCodeEnum.WORK_FLOW_CONTENT_ERROR.getException(var5.getMessage());
        }
    }

    /**
     * 评审流程
     *
     * @param flowObject
     * @return
     */
    public void extendedTask(FlowObject flowObject) {


        TyplmPartService typlmPartService = SpringUtil.getBean(TyplmPartService.class);


        BigInteger oid = flowObject.getRefObjectOid();
        String oType = flowObject.getRefObjectOtype();
        PartDetailsVO partDetailsVO = typlmPartService.queryPartDetails(oid, oType);

        TyplmPartBomService typlmPartBomService = SpringUtil.getBean(TyplmPartBomService.class);
        if (typlmPartBomService != null) {
            com.hustcad.plm.pdm.partbom.dto.ExpandBomTreeByFilterDTO expandBomTreeByFilterDTO = new com.hustcad.plm.pdm.partbom.dto.ExpandBomTreeByFilterDTO();
            expandBomTreeByFilterDTO.setFatherOid(String.valueOf(partDetailsVO.getOid()));
            expandBomTreeByFilterDTO.setExpandLevel("N");
            expandBomTreeByFilterDTO.setGiveUsesOccurrence("N");
            expandBomTreeByFilterDTO.setIsQueryIBA(true);
            expandBomTreeByFilterDTO.setIsNestedTree(false);

            ChildPartsFiltersDTO childPartsFiltersDTO = new ChildPartsFiltersDTO();
            childPartsFiltersDTO.setView(partDetailsVO.getView());
            childPartsFiltersDTO.setExpandCondition("latest");
            List<ChildPartsFiltersDTO> list = new ArrayList<>();
            list.add(childPartsFiltersDTO);
            expandBomTreeByFilterDTO.setConditions(list);
            PartBomTreeByFilterVO result = typlmPartBomService.expandBomTreeByFilterNew(expandBomTreeByFilterDTO,
                                                                                        Boolean.TRUE);

            List<String> checkErrorList=new ArrayList<>();
            List<String> erpErrorList=new ArrayList<>();
            List<String> erpTypeErrorList=new ArrayList<>();

            for (int y = 0; y < result.getPartBomTreeList().size(); y++) {
                PartBomTree partBomTree = result.getPartBomTreeList().get(y);
                if (partBomTree.getOid() != BigInteger.valueOf(0L)) {
                    if("c/i".equals(partBomTree.getCheckInOrCheckOut())==false){
                        checkErrorList.add(partBomTree.getObjectNumber());
                    }
                    if("ERP不管控零部件".equals(partBomTree.getTypeName())){
                        erpErrorList.add(partBomTree.getObjectNumber());
                    }
                    if(partBomTree.getIsLeafNode()==false){
                        BigInteger coid = new BigInteger(partBomTree.getPartoid());
                        String coType = partBomTree.getPartotype();
                        PartDetailsVO partDetails = typlmPartService.queryPartDetails(coid, coType);
                        Map<String, List<String>> attrMap=partDetails.getIbaAttributeMap();
                        if(attrMap.containsKey("物料属性")){
                            List<String> attr=attrMap.get("物料属性");
                            if("1".equals(attr.get(0))){
                                erpTypeErrorList.add(partBomTree.getObjectNumber());
                            }
                        }
                    }
                }
            }

            if(checkErrorList.size()>0 && checkErrorList.size()>0 && erpTypeErrorList.size()>0){
                throw SystemErrorCodeEnum.WORK_FLOW_CONTENT_ERROR.getException("零部件对象被检出或锁定"+ JSONObject.toJSONString(checkErrorList)+" BOM数据中有ERP不管控类型"+ JSONObject.toJSONString(erpErrorList)
                                                                                       +" 不能使用外购件创建BOM"+ JSONObject.toJSONString(erpTypeErrorList));
            }
            else{
                if(checkErrorList.size()>0){
                    throw SystemErrorCodeEnum.WORK_FLOW_CONTENT_ERROR.getException("零部件对象被检出或锁定"+ JSONObject.toJSONString(checkErrorList));
                }
                if(erpErrorList.size()>0){
                    throw SystemErrorCodeEnum.WORK_FLOW_CONTENT_ERROR.getException("BOM数据中有ERP不管控类型"+ JSONObject.toJSONString(erpErrorList));
                }
                if(erpTypeErrorList.size()>0){
                    throw SystemErrorCodeEnum.WORK_FLOW_CONTENT_ERROR.getException("不能使用外购件创建BOM"+ JSONObject.toJSONString(erpTypeErrorList));
                }
            }

        }
    }

    /**
     * 变更流程
     *
     * @param ecObjData
     * @return
     */
    public void extendedTaskEco(ECObjData ecObjData) {

        TyplmBaseLineMemberService typlmBaseLineMemberService = SpringUtil.getBean(TyplmBaseLineMemberService.class);
        TyplmBaseLineService typlmBaseLineService = SpringUtil.getBean(TyplmBaseLineService.class);
        TyplmPartService typlmPartService = (TyplmPartService) SpringUtil.getBean(
                TyplmPartService.class);
        if ("ty.inteplm.part.CTyPart".equals(ecObjData.getOtype()) == false) {
            throw SystemErrorCodeEnum.WORK_FLOW_CONTENT_ERROR.getException(ecObjData.getObjectNumber()+" 不是零部件对象");
        }

        BigInteger oid = ecObjData.getRefObjectOid();
        String oType = ecObjData.getRefObjectOtype();
        PartDetailsVO partDetailsVO = typlmPartService.queryPartDetails(oid, oType);

        TyplmPartBomService typlmPartBomService = SpringUtil.getBean(TyplmPartBomService.class);
        if (typlmPartBomService != null) {
            com.hustcad.plm.pdm.partbom.dto.ExpandBomTreeByFilterDTO expandBomTreeByFilterDTO = new com.hustcad.plm.pdm.partbom.dto.ExpandBomTreeByFilterDTO();
            expandBomTreeByFilterDTO.setAttrFilterCondition(new ArrayList<>());

            ChildPartsFiltersDTO childPartsFiltersDTO = new ChildPartsFiltersDTO();
            childPartsFiltersDTO.setBaseLineOid("");
            childPartsFiltersDTO.setDate("");
            childPartsFiltersDTO.setExpandCondition("latest");
            childPartsFiltersDTO.setLifecycleStateKey("");
            childPartsFiltersDTO.setPurposeOfBom("");
            childPartsFiltersDTO.setSpareBom("");
            childPartsFiltersDTO.setView(partDetailsVO.getView());
            List<ChildPartsFiltersDTO> list = new ArrayList<>();
            list.add(childPartsFiltersDTO);
            expandBomTreeByFilterDTO.setConditions(list);

            expandBomTreeByFilterDTO.setExpandLevel("N");
            expandBomTreeByFilterDTO.setFatherNumber(partDetailsVO.getObjectNumber());
            expandBomTreeByFilterDTO.setFatherOid(String.valueOf(partDetailsVO.getOid()));
            expandBomTreeByFilterDTO.setFatherOtype(partDetailsVO.getOtype());
            expandBomTreeByFilterDTO.setFilterMode("0");
            expandBomTreeByFilterDTO.setGiveUsesOccurrence("N");
            expandBomTreeByFilterDTO.setIbaColumns(new ArrayList<>());
            expandBomTreeByFilterDTO.setIsApplyRoot(false);
            expandBomTreeByFilterDTO.setIsFilterAttr(false);
            expandBomTreeByFilterDTO.setIsNeedTranEnum(true);
            expandBomTreeByFilterDTO.setIsNestedTree(false);
            expandBomTreeByFilterDTO.setIsQueryIBA(true);

            PartBomTreeByFilterVO result = typlmPartBomService.expandBomTreeByFilterNew(expandBomTreeByFilterDTO,
                                                                                        Boolean.TRUE);

            List<String> checkErrorList=new ArrayList<>();
            List<String> erpErrorList=new ArrayList<>();
            List<String> erpTypeErrorList=new ArrayList<>();

            for (int y = 0; y < result.getPartBomTreeList().size(); y++) {
                PartBomTree partBomTree = result.getPartBomTreeList().get(y);
                if (partBomTree.getOid() != BigInteger.valueOf(0L)) {
                    if("c/i".equals(partBomTree.getCheckInOrCheckOut())==false){
                        checkErrorList.add(partBomTree.getObjectNumber());
                    }
                    if("ERP不管控零部件".equals(partBomTree.getTypeName())){
                        erpErrorList.add(partBomTree.getObjectNumber());
                    }
                    if(partBomTree.getIsLeafNode()==false){
                        BigInteger coid = new BigInteger(partBomTree.getPartoid());
                        String coType = partBomTree.getPartotype();
                        PartDetailsVO partDetails = typlmPartService.queryPartDetails(coid, coType);
                        Map<String, List<String>> attrMap=partDetails.getIbaAttributeMap();
                        if(attrMap.containsKey("物料属性")){
                            List<String> attr=attrMap.get("物料属性");
                            if("1".equals(attr.get(0))){
                                erpTypeErrorList.add(partBomTree.getObjectNumber());
                            }
                        }
                    }
                }
            }

            if(checkErrorList.size()>0 && checkErrorList.size()>0 && erpTypeErrorList.size()>0){
                throw SystemErrorCodeEnum.WORK_FLOW_CONTENT_ERROR.getException("零部件对象被检出或锁定"+ JSONObject.toJSONString(checkErrorList)+" BOM数据中有ERP不管控类型"+ JSONObject.toJSONString(erpErrorList)
                                                                                       +" 不能使用外购件创建BOM"+ JSONObject.toJSONString(erpTypeErrorList));
            }
            else{
                if(checkErrorList.size()>0){
                    throw SystemErrorCodeEnum.WORK_FLOW_CONTENT_ERROR.getException("零部件对象被检出或锁定"+ JSONObject.toJSONString(checkErrorList));
                }
                if(erpErrorList.size()>0){
                    throw SystemErrorCodeEnum.WORK_FLOW_CONTENT_ERROR.getException("BOM数据中有ERP不管控类型"+ JSONObject.toJSONString(erpErrorList));
                }
                if(erpTypeErrorList.size()>0){
                    throw SystemErrorCodeEnum.WORK_FLOW_CONTENT_ERROR.getException("不能使用外购件创建BOM"+ JSONObject.toJSONString(erpTypeErrorList));
                }
            }
        }



    }

}
